import { LoadingController, ToastController } from "ionic-angular";
import { Injectable } from "@angular/core";
import { appConfig } from "./config";
import {
  ThemeableBrowser,
  ThemeableBrowserOptions
} from "@ionic-native/themeable-browser";
import * as _ from "lodash";
import * as moment from "moment";
import { Network } from "@ionic-native/network";

interface User {
  name: string;
  tel: string;
  org: string;
}
@Injectable()
export class CommonFunc {
  constructor(
    private loading: LoadingController,
    private toast: ToastController,
    private themeableBrowser: ThemeableBrowser,
    private network: Network
  ) { }

  /**
   * 判断是否有网络
   */
  hasNetWork() {
    if (this.network.type === "none") {
      return false;
    } else {
      return true;
    }
  }

  /**
   * showLoading: 展示loading
   */
  showLoading(loadingOpt) {
    var loading = this.loading.create({
      spinner: loadingOpt.spinner || appConfig.spinner,
      content: loadingOpt.content,
      duration: loadingOpt.duration || 3000,
      dismissOnPageChange: loadingOpt.dismissOnPageChange || true
    });

    return loading;
  }

  /**
   * showToast: 展示toast
   */
  showToast(toastOpt) {
    var toast = this.toast.create({
      message: toastOpt.message,
      duration: toastOpt.duration || 3000,
      position: toastOpt.position || "top",
      cssClass: toastOpt.cssClass || "custom-toast",
      showCloseButton: toastOpt.showCloseBtn || false,
      closeButtonText: toastOpt.closeBtnText || "",
      dismissOnPageChange: toastOpt.dismissOnPageChange || true
    });

    return toast;
  }

  /**
   * showBlankToast: 返回数据为空时显示
   */
  showBlankToast() {
    let toastOpt = {
      message: "数据为空",
      duration: 1500
    };
    let toast = this.showToast(toastOpt);
    return toast;
  }

  /**
   * showInsideErrorToast: 接口通畅，返回报错时显示
   */
  showInsideErrorToast(data) {
    let toastOpt = {
      message: data["errorMessage"]
    };
    let toast = this.showToast(toastOpt);
    return toast;
  }

  /**
   * showOutsideErrorToast: 接口不通畅，返回报错时提示
   */
  showOutsideErrorToast(error) {
    let toastOpt = {
      message: error
    };
    let toast = this.showToast(toastOpt);
    return toast;
  }

  /**
   * draw2dVcard: 生成个人信息二维码
   */
  draw2dVcard(targetId: string, content: User, size: number) {
    size = size || 128;
    var VcardText =
      "BEGIN:VCARD\nN:" +
      content.name +
      "\nTEL:" +
      content.tel +
      "\nORG:" +
      content.org +
      "\nEND:VCARD";
    new window["QRCode"](document.getElementById(targetId), {
      text: VcardText,
      width: size,
      height: size
    });
  }

  changeCheckBox($event) {
    let currentCheck = $event.target;
    if (currentCheck.checked) {
      let checkboxs = currentCheck.parentNode.getElementsByTagName("input");
      for (let i = 0; i < checkboxs.length; i++) {
        if (checkboxs[i].checked) {
          checkboxs[i].checked = false;
        }
      }
      currentCheck.checked = true;
      return currentCheck.value;
    }
    return null;
  }

  /**
   * handleItems: 处理宫格每行显示饱满个数item
   */
  handleItems(items, rowItems) {
    let residue = items.length % rowItems;
    if (residue === 0) {
      items = _.chunk(items, rowItems); // 按rowItems分组
      return items;
    }

    let start = items.length + 1;
    let end = items.length + rowItems - residue;

    for (let i = start; i <= end; i++) {
      items.push({}); // 补足items
    }

    items = _.chunk(items, rowItems); // 按rowItems分组

    return items;
  }

  /**
   * 校验邮箱
   * @param param
   * @returns {boolean}
   */
  checkEmail(param) {
    var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    return reg.test(param);
  }

  /**
   * 校验手机号
   * @param param
   * @returns {boolean}
   */
  checkMobile(param) {
    var reg = /^1[3|4|5|7|8][0-9]{9}$/;
    return reg.test(param);
  }

  /**
   * 校验身份证
   * @param param
   * @returns {boolean}
   */
  checkCard(param) {
    var reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    return reg.test(param);
  }

  /**
   * 日期转换
   */
  stringParseDate(param) {
    return (
      param.substring(0, 4) +
      "-" +
      param.substring(4, 6) +
      "-" +
      param.substring(6, 8)
    );
  }

  //移除数组中的某个元素
  removeArrayValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  }

  //验身份证是否争取
  checkCardObject(sId) {
    let card_area = {
      11: "北京",
      12: "天津",
      13: "河北",

      14: "山西",
      15: "内蒙古",
      21: "辽宁",

      22: "吉林",
      23: "黑龙江",
      31: "上海",

      32: "江苏",
      33: "浙江",
      34: "安徽",

      35: "福建",
      36: "江西",
      37: "山东",

      41: "河南",
      42: "湖北",
      43: "湖南",

      44: "广东",
      45: "广西",
      46: "海南",

      50: "重庆",
      51: "四川",
      52: "贵州",

      53: "云南",
      54: "西藏",
      61: "陕西",

      62: "甘肃",
      63: "青海",
      64: "宁夏",

      65: "新疆",
      71: "台湾",
      81: "香港",

      82: "澳门",
      91: "国外"
    };

    let iSum = 0;

    let card_info: any = [];

    sId = sId.replace(/x$/i, "a");

    if (sId.length == 0) {
      card_info[0] = false;
      card_info[1] = "请填写你的身份证";
      return card_info;
    }

    if (card_area[parseInt(sId.substr(0, 2))] == null) {
      card_info[0] = false;
      card_info[1] = "非法证件你的地区填写有错误请仔细填写";
      return card_info;
    }

    let sBirthday =
      sId.substr(6, 4) +
      "-" +
      Number(sId.substr(10, 2)) +
      "-" +
      Number(sId.substr(12, 2));

    let d = new Date(sBirthday.replace(/-/g, "/"));

    if (
      sBirthday !=
      d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()
    ) {
      card_info[0] = false;
      card_info[1] = "非法证件你的生日填写有错误请仔细填写";
      return card_info;
    }

    for (var i = 17; i >= 0; i--) {
      iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
    }

    if (iSum % 11 != 1) {
      card_info[0] = false;
      card_info[1] = "非法证件";
      return card_info;
    }

    if (sId.length > 19) {
      card_info[0] = false;
      card_info[1] = "你确认你的身份证是有效证件";
      return card_info;
    }

    card_info[0] = true;
    card_info[1] = card_area[parseInt(sId.substr(0, 2))];

    card_info[2] = sBirthday;

    card_info[3] = sId.substr(16, 1) % 2 ? "1" : "2";

    return card_info;
  }

  showTimeLoading() {
    let loading = this.loading.create({
      spinner: appConfig.spinner,
      duration: appConfig.timeout
    });
    return loading;
  }

  //url, title, description, thumb, type
  shareToWechat(wechatObj: Object) {
    //开始微信分享
    let wechat = (<any>window).Wechat;

    let scene: any = null;
    if (wechatObj["type"] == 1) {
      scene = wechat.Scene.SESSION;
    } else if (wechatObj["type"] == 2) {
      scene = wechat.Scene.TIMELINE;
    } else {
      return;
    }

    //判断微信有没有
    wechat.isInstalled(
      installed => {
        if (!installed) {
          let toastOpt = {
            message: "您没有安装微信！",
            duration: 1500
          };
          let toast = this.showToast(toastOpt);
          toast.present();
          return;
        }
      },
      function (reason) {
        let toastOpt = {
          message: "失败: " + reason,
          duration: 1500
        };
        let toast = this.showToast(toastOpt);
        toast.present();
        return;
      }
    );
    //分享
    wechat.share(
      {
        message: {
          title: wechatObj["title"],
          description: wechatObj["description"],
          thumb: wechatObj["thumb"],
          media: {
            type: wechat.Type.WEBPAGE,
            webpageUrl: wechatObj["url"]
          }
        },
        scene: scene
      },
      function () {
        let toastOpt = {
          message: "分享成功",
          duration: 1500
        };
        let toast = this.showToast(toastOpt);
        toast.present();
      },
      function (reason) {
        let toastOpt = {
          message: reason,
          duration: 1500
        };
        let toast = this.showToast(toastOpt);
        toast.present();
      }
    );
  }

  /**
   * 将 bean中 json对象 转为 json字符串  ；
   */

  convertBeanToString(bean: any = {}) {
    let beanC = {};
    for (var key in bean) {
      if (bean.hasOwnProperty(key)) {
        let value = bean[key];
        let vin: any;
        vin = value;
        if (vin) {
          if (value["picUrl"] != undefined) {
            if (vin["picUrl"]) {
              vin["picUrl"] = vin["picUrl"].join(",");
            }
            vin = JSON.stringify(value);
          }
        }
        beanC[key] = vin;
      }
    }
    return beanC;
  }

  convertBean(bean: any = {}) {
    let beanC = {};
    for (var key in bean) {
      if (bean.hasOwnProperty(key)) {
        let value = bean[key] + "";
        let vin: any;
        vin = value;
        if (value.startsWith("{") && value.endsWith("}")) {
          vin = JSON.parse(value);
          if (vin["picUrl"]) {
            vin["picUrl"] = vin["picUrl"].split(",");
          } else {
            vin["picUrl"] = [];
          }
        }
        beanC[key] = vin;
      }
    }
    return beanC;
  }

  //交验
  vlidate(bean: Object, list: Array<String>, ckeck: boolean) {
      try {
          for (var key in bean) {
              let value = bean[key];
              if (list.length > 0) {
                  if (list.indexOf(key) != -1) {
                      if (value["picUrl"].length <= 0) {
                          return false;
                      }
                  }
              }
              // if (ckeck) {
              if (value.isOk != undefined && value.isOk != null) {
                  if (value["isOk"] + "" === "false") {
                      if (value.remark != undefined) {
                          if (!value["remark"] || value["remark"].length <= 0) {
                              return false;
                          }
                      }
                      if (value.remarks != undefined) {
                          if (!value["remarks"] || value["remarks"].length <= 0) {
                              return false;
                          }
                      }
                  }
              }
              // }

          }
      } catch (e) {
        console.log(e.message);
        return true;
      }
    return true;
  }

  //删除数组中的某个元素
  removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  }

  transformtime(value) {
    if (!value) {
      return null;
    }
    let values = value + "";
    let date = values.substring(0, 8);
    let time = values.substring(8, 14);
    let dates = moment(date).format("YYYY-MM-DD");
    let times =
      time.substring(0, 2) +
      ":" +
      time.substring(2, 4) +
      ":" +
      time.substring(4, 6);

    return dates + " " + times;
  }

  toappstore(url) {
    this.themeableBrowser.create(url, "_system", {});
  }

  openUrl(url) {
    const options: ThemeableBrowserOptions = {
      statusbar: { color: "#ffffffff" },
      toolbar: { height: 44, color: "#f0f0f0ff" },
      title: { color: "#003264ff", staticText: "查看" },
      closeButton: {
        wwwImage: "assets/icon/left.png",
        wwwImagePressed: "assets/icon/left.png",
        wwwImageDensity: 1,
        align: "left",
        event: "closePressed"
      },
      backButtonCanClose: true
    };
    this.themeableBrowser.create(url, "_blank", options);
  }

  openDocs(url) {
    let list: Array<string> = [
      "doc",
      "dot",
      "docx",
      "dotx",
      "docm",
      "dotm",
      "xls",
      "xlt",
      "xla",
      "xlsx",
      "xltx",
      "xlsm",
      "xltm",
      "xlam",
      "xlsb",
      "ppt",
      "pot",
      "pps",
      "ppa",
      "pptx",
      "potx",
      "ppsx",
      "ppam",
      "pptm",
      "potm",
      "ppsm"
    ];
    let lookUrl = "";
    let tt = url.split(".");
    let houzui = null;
    if (tt.length > 1) {
      houzui = tt[tt.length - 1];
    }
    if (houzui) {
      if (list.indexOf(houzui) >= 0) {
        lookUrl = appConfig.OFFICE_URL + appConfig.PREVIEW_URL + url;
      } else {
        lookUrl = appConfig.PREVIEW_URL + url;
      }
    } else {
      lookUrl = appConfig.PREVIEW_URL + url;
    }
    const options: ThemeableBrowserOptions = {
      statusbar: { color: "#ffffffff" },
      toolbar: { height: 44, color: "#f0f0f0ff" },
      title: { color: "#003264ff", staticText: "文件查看" },
      closeButton: {
        wwwImage: "assets/icon/left.png",
        wwwImagePressed: "assets/icon/left.png",
        wwwImageDensity: 1,
        align: "left",
        event: "closePressed"
      },
      backButtonCanClose: true
    };
    this.themeableBrowser.create(lookUrl, "_blank", options);
  }
}
